<script setup>
import { fetchGoodsList } from '@/api/goods'
import { onMounted, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'

// 使用defineModel替代props和emit
const selectedGoods = defineModel('selectedGoods', {
  type: Array,
  default: () => [],
})

// 表格引用，用于控制选中状态
const tableRef = ref(null)

const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const queryFields = ref({
  goodsName: '',
  dealerGoodsTypeName: '',
})

// 获取商品列表
const fetchGoods = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      queryFields: {
        goodsName: queryFields.value.goodsName.trim() || null,
        dealerGoodsTypeName: queryFields.value.dealerGoodsTypeName.trim() || null,
      },
    }
    const res = await fetchGoodsList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0

      // 在表格数据更新后应用选中状态
      nextTick(() => {
        applySelection()
      })
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    logger.error('获取商品列表失败', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  fetchGoods()
}

// 重置搜索条件
const resetSearch = () => {
  queryFields.value.goodsName = ''
  queryFields.value.dealerGoodsTypeName = ''
  currentPage.value = 1
  fetchGoods()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGoods()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGoods()
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  // 获取当前页的行数据
  const currentPageRows = tableData.value || []
  const currentPageIds = currentPageRows.map((item) => String(item.dealerGoodsId))

  // 保留不在当前页的已选项
  const itemsNotInCurrentPage = selectedGoods.value.filter(
    (item) => !currentPageIds.includes(String(item.dealerGoodsId)),
  )

  // 添加当前页中选中的项
  const selectedFromCurrentPage = selection

  // 合并不在当前页的选中项和当前页新选中的项
  selectedGoods.value = [...itemsNotInCurrentPage, ...selectedFromCurrentPage]
}

// 应用已选商品到表格
const applySelection = () => {
  if (!tableRef.value) return

  // 清除当前表格的选中状态
  tableRef.value.clearSelection()

  // 获取当前页的行数据
  const currentPageRows = tableData.value || []

  // 当前选中的ID列表
  const selectedIds = selectedGoods.value.map((item) => String(item.dealerGoodsId))

  // 应用选中状态到当前页的行
  currentPageRows.forEach((row) => {
    if (selectedIds.includes(String(row.dealerGoodsId))) {
      nextTick(() => {
        tableRef.value.toggleRowSelection(row, true)
      })
    }
  })
}

// 新增：定义emit事件（补充 close 以便父组件关闭弹窗）
const emit = defineEmits(['confirm', 'cancel', 'close'])

// 新增：确定和取消按钮事件（同时触发 close 让父组件关闭弹窗）
const onConfirm = () => {
  emit('confirm', selectedGoods.value)
  emit('close')
}
const onCancel = () => {
  emit('cancel')
  emit('close')
}

onMounted(() => {
  fetchGoods()
})
</script>

<template>
  <div class="goods-selector">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryFields">
        <el-form-item label="商品名称">
          <el-input
            v-model="queryFields.goodsName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品类别">
          <el-input
            v-model="queryFields.dealerGoodsTypeName"
            placeholder="请输入商品类别"
            clearable
            style="width: 180px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><LineMdSearch /></el-icon>
            </template>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-key="(row) => row.dealerGoodsId"
      >
        <el-table-column reserve-selection type="selection" width="55" align="center" />
        <el-table-column label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 50px; height: 50px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" min-width="120" align="center" />
        <el-table-column label="商品类别" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag>{{ row.dealerGoodsTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="配送费（元）" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.shippingFee }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="免配送数量（件）" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.freeShipping }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success">{{ row.specifications }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="80" align="center" />
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <div class="action-container">
      <el-button @click="onCancel">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        取消
      </el-button>
      <el-button type="primary" @click="onConfirm">
        <template #icon>
          <el-icon><LineMdCheckAll /></el-icon>
        </template>
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.goods-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  height: calc(100vh - 200px);
  gap: 10px;

  .search-container {
    border: 1px solid #ebeef5;
    border-radius: 10px;
    background-color: #fff;
  }

  .table-wrapper {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 10px;
    background-color: #fff;
    padding: 15px;
    border-radius: 10px;

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-container {
    display: flex;
    justify-content: flex-end;
    background-color: #fff;
    border-radius: 10px;
  }

  .no-image {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #f5f7fa;
    font-size: 12px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
}
</style>
